<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/11/16
 * Time: 14:14
 */
namespace App\Service\Admin;

use App\Http\Model\Mysql\AnchorModel;
use Carbon\Carbon;

class AnchorService extends BaseService
{
    /**
     * 主播列表
     * @param int|null $limit
     * @param int $page
     * @return array
     */
    public function anchorList(int $limit = null, int $page = 1)
    {
        $limit  =   empty($limit) ? self::PAGE_LIMIT : $limit;
        $count  =   AnchorModel::query()->useful()->count();
        $list   =   AnchorModel::query()->useful()->offset(($page - 1) * $limit)->limit($limit)->select(['id', 'nick_name', 'head_icon', 'followers', 'unique_id'])->get()->each(function (&$item) {

                    });

        if ($list->isEmpty()) {
            return [true, []];
        } else {
            return [true, [
                'count' =>  $count,
                'list'  =>  $list->toArray(),
                'pages' =>  ceil($count / $limit),
                'current'=> $page
            ]];
        }
    }

    /**
     * 主播添加
     * @param array $params
     * @return array
     */
    public function anchorAdd(array $params)
    {
        $anchor['unique_id']    =   createUniqueID();
        $anchor['nick_name']    =   $params['nick_name'];
        $anchor['head_icon']    =   $params['head_icon'] ?? '';
        $result =   AnchorModel::create($anchor);
        if ($result) {
            return [true, '添加成功'];
        } else {
            return [false, '添加失败'];
        }
    }

    /**
     * 删除主播
     * @param int $anchor_id
     * @return array
     */
    public function anchorDelete(int $anchor_id)
    {
        $result =   AnchorModel::where(['id' => $anchor_id])->update(['is_delete' => AnchorModel::IS_DELETE, 'delete_time' => Carbon::now()->timestamp]);
        if ($result) {
            return [true, '删除成功'];
        } else {
            return [false, '删除失败'];
        }
    }

    /**
     * 主播编辑
     * @param array $params
     * @param int $anchor_id
     * @return array
     */
    public function anchorEdit(array $params, int $anchor_id)
    {
        $anchor['nick_name']    =   $params['nick_name'];
        $anchor['head_icon']    =   $params['head_icon'] ?? '';
        $result =   AnchorModel::where(['id' => $anchor])->update($anchor);
        if ($result) {
            return [true, '编辑成功'];
        } else {
            return [false, '编辑失败'];
        }
    }
}
